package com.rytong.tools.offstore;

import java.util.ArrayList;
import java.util.List;

import com.rytong.tools.utils.Utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class OffStoreDB extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "emp.db";
    private static int DATABASE_VERSION = 1;
    private static String TABLE_NAME = "emp_table";
    private static String COLUMN_ID = "_id";
    private static String COLUMN_NAME = "name";
    private static String COLUMN_VALUE = "value";
    // 离线资源数据库
    public static OffStoreDB OFFLINEDB;
    // 插件数据库
    public static OffStoreDB PLUGDB;

    public OffStoreDB(Context context, String name) {
        super(context, name, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table ".concat(TABLE_NAME).concat("(").concat(COLUMN_ID)
                .concat(" integer primary key autoincrement,").concat(COLUMN_NAME).concat(" varchar(100),")
                .concat(COLUMN_VALUE).concat(" varchar(300))"));
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS ".concat(TABLE_NAME));
        onCreate(db);
    }

    public long insert(String column_name, Object column_value) {
        long row = 0;
        SQLiteDatabase db = this.getWritableDatabase();
        try{
            ContentValues cv = new ContentValues();
            
            cv.put(COLUMN_NAME, column_name);
            
            if (column_value instanceof String)
                cv.put(COLUMN_VALUE, (String) column_value);
            else if (column_value instanceof byte[])
                cv.put(COLUMN_VALUE, (byte[]) column_value);
            
            row= db.insert(TABLE_NAME, null, cv);
        }catch(Exception e){
            Utils.printException(e);
        }finally{
            if(db.isOpen()){
                db.close();
            }
        }
        return row;
    }

    public List<Object> getListByColumnName() {
        List<Object> result = new ArrayList<Object>();
        SQLiteDatabase db = getReadableDatabase();
        String dbString = "";
        Cursor cursor = null;
        try {
            dbString = "SELECT "+ COLUMN_NAME +" FROM ".concat(TABLE_NAME);
            cursor = db.rawQuery(dbString, null);
            int index = cursor.getColumnIndex(COLUMN_NAME);
            
            while(cursor.moveToNext()){
                result.add(new String(cursor.getString(index).getBytes() , "UTF-8"));
            }
        } catch (Exception e) {
            Utils.printException(e);
        } finally{
            if(!cursor.isClosed()){
                cursor.close();
            }
            if(db.isOpen()){
                db.close();
            }
        }
        return result;
    }

    public int deleteToDB(String fileName) {
        SQLiteDatabase db = this.getWritableDatabase();
        int row = 0;
        try{
            row = db.delete(TABLE_NAME, COLUMN_NAME + "=?", new String[] { fileName });
        }catch(Exception e){
            Utils.printException(e);
        }finally{
            if(db.isOpen()){
                db.close();
            }
        }
        return row;
    }

    public static void saveToDb(OffStoreDB db, String key, Object value) {
        db.insert(key, value);
    }

    /**
     * 不联网情况下个别页面读取本地数据库XML
     * 
     * @param itemValue
     * @param currentView_
     * @return
     */
    public static Object readOfflineResource(OffStoreDB db, String itemValue) {
        return db.find(itemValue);
    }
    
    public Object find(String columValue) {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = null;
        Object value = null;
        try {
            String dbString = "SELECT * FROM ".concat(TABLE_NAME).concat(" WHERE ").concat(COLUMN_NAME).concat(" = ?");
            cursor = db.rawQuery(dbString, new String[] { columValue });
            if (cursor.moveToFirst()) {
                // 如果是图片将会被保存为字节数组形式
                value = cursor.getBlob(cursor.getColumnIndex(COLUMN_VALUE));
            }
        } catch (Exception e) {
            Utils.printException(e);
        } finally{
            if(!cursor.isClosed()){
                cursor.close();
            }
            if(db.isOpen()){
                db.close();
            }
        }
        return value;
    }
    
    public static String readOffline(OffStoreDB db, String itemValue) {
        return db.findImage(itemValue);
    }
    
    public String findImage(String columValue) {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = null;
        String value = null;
        try {
            String dbString = "SELECT * FROM ".concat(TABLE_NAME).concat(" WHERE ").concat(COLUMN_NAME).concat(" like ?");
            cursor = db.rawQuery(dbString, new String[] {"%" + columValue + "%"});
            if (cursor.moveToFirst()) {
                // 如果是图片将会被保存为字节数组形式
                value = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
            }
        } catch (Exception e) {
            Utils.printException(e);
        } finally{
            if(!cursor.isClosed()){
                cursor.close();
            }
            if(db.isOpen()){
                db.close();
            }
        }
        return value;
    }
}
